<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>贪吃蛇</title>
		<style type="text/css">
			*{margin: 0;padding: 0;}
			body{
				background-color: #000000;
			}
			.snake{
				width: 20px;
				height: 20px;
				background-color: #FFFFFF;
				position: fixed;
				top: 0;
				left: 0;
			}
		</style>
	</head>
	<body>
		<div class="snake" id="snake"></div>
		
		<script type="text/javascript">
			//浏览器的宽
			var windowX = window.innerWidth;
			//初始坐标
			var snakeX = 0;
			var snakeY = 0;
			//定义四个变量 布尔类型
			var goLeft = false;
			var goRight = true;
			var goTop = false;
			var goBottom = false;
			
			//通过id找标签
			var snake = document.getElementById("snake");
			
			//键盘按下触发函数
			document.onkeydown = function(event){
				//固定语法
				event = event || window.event;
				//获取键盘状态码
				var number = event.keyCode;
				//打印
				
				if(number == 37){//左
					stopMove();
					goLeft = true;
				}else if(number == 38){//上
					stopMove();
					goTop = true;
				}else if(number == 39){//右
					stopMove();
					goRight = true;
				}else if(number == 40){//下
					stopMove();
					goBottom = true;
				}else if(number == 81){//Q
					snake.style.width = "50px";
					snake.style.height = "50px";
				}else if(number == 87){//W
					snake.style.width = "20px";
					snake.style.height = "20px";
				}else if(number == 69){//E
					snake.style.borderRadius = "50%";
				}else if(number == 82){//R
					snake.style.borderRadius = "0%";
				}
			}
			function stopMove(){//停止所有方向
				//先清除所有方向
				goLeft = false;
				goTop = false;
				goRight = false;
				goBottom = false;
			}
			
			//贪吃蛇的发动机
			setInterval(function(){
				if(goLeft){//左
					snakeX--;
					//左边出
					if(snakeX == -20){
						snakeX = windowX
					}
				}
				if(goRight){//右
					snakeX++;
					//判断是否超出屏幕 右边出
					if(windowX == snakeX){
						snakeX = -20;
					}
				}
				if(goTop){//上
					snakeY--;
				}
				if(goBottom){//下
					snakeY++;
				}
				
				//修改样式  对象.style
				snake.style.left = snakeX + "px";
				snake.style.top = snakeY + "px";
			},1);
			
		</script>
	</body>
</html>
